const Router = require('koa-router');
const router = new Router();
const tool = require('../../tools/tool')
const {db, QueryTypes} = require("../../models/db");
const tools = require("../../tools/tool");

router.post('/zq/fj', async ctx => {
    try {
        let user = ctx.user
        let body = ctx.request.body
        let tenantId = user.tenantId;
        let zqId = body.zqId;
        let ctime = tools.getTime()
        if (!zqId) {
            return ctx.err('会计期间不能为空');
        }
        let zq = await db.models['zq'].findOne({
            where: {
                id: zqId
            }
        })
        if (!zq) {
            return ctx.err('账期设置错误')
        }
        await db.transaction(async () => {
            await db.models['zq'].destroy({
                where: {
                    tenantId,
                    id: zqId
                }
            }, )
            let zq1 = await db.models['zq'].findOne({
                where: {
                    tenantId
                },
                order: [['id', 'desc']]
            })
            if(zq1) {
                await db.models['zq'].update({
                    isCurrent: 1,
                    ctime
                }, {
                    where: {
                        id: zq1.id
                    }
                }, )
            }
            else {
                await db.models['inventory'].destroy({
                    where: {
                        tenantId
                    }
                })
                await db.models['inventoryDetail'].destroy({
                    where: {
                        tenantId
                    }
                })
            }
            if(ctx.user.isCard == 1) {
                let sql = `delete from card_info where cardId in(select id from card where zqId=${zqId} and isJz=1 and tenantId=${tenantId})`;
                await db.query(sql, {type: QueryTypes.UPDATE}, )
                await db.models['card'].destroy({
                    where: {
                        tenantId,
                        zqId,
                        isJz: 1
                    }
                }, )
            }
            // await db.query(sqls, {type: QueryTypes.UPDATE}, )
        })
        return ctx.suc('反结成功');

    } catch (e) {
        return ctx.err('操作失败')
    }
})

module.exports = router;
